package com.example.show_auto.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.SimpleDateFormat
import java.util.*

/**
 * 多用户个人数据管理器
 * 支持多个用户的个人数据存储和管理
 */
class MultiUserDataManager(private val context: Context) {
    
    private val sharedPrefs: SharedPreferences = 
        context.getSharedPreferences("multi_user_data", Context.MODE_PRIVATE)
    private val gson = Gson()
    
    companion object {
        private const val KEY_CURRENT_USER = "current_user"
        private const val KEY_USER_LIST = "user_list"
        private const val KEY_USER_ORDER = "user_order"
        private const val KEY_USER_DATA_PREFIX = "user_data_"
        
        /**
         * 生成用户唯一标识
         */
        fun generateUserId(): String {
            return "user_${System.currentTimeMillis()}_${(1000..9999).random()}"
        }
    }
    
    /**
     * 用户数据模型
     */
    data class UserData(
        val userName: String,
        val personalDataJson: String,
        val validationCode: String,
        val createTime: Long = System.currentTimeMillis(),
        val lastUpdateTime: Long = System.currentTimeMillis(),
        val userId: String = "" // 用户唯一标识
    )
    
    /**
     * 保存用户数据
     */
    fun saveUserData(userName: String, personalDataJson: String, validationCode: String): Boolean {
        return try {
            val userData = UserData(
                userName = userName,
                personalDataJson = personalDataJson,
                validationCode = validationCode,
                lastUpdateTime = System.currentTimeMillis(),
                userId = generateUserId() // 为新用户生成唯一ID
            )
            
            // 保存用户数据
            sharedPrefs.edit()
                .putString("$KEY_USER_DATA_PREFIX$userName", gson.toJson(userData))
                .apply()
            
            // 更新用户列表
            val userList = getAllUserNames().toMutableList()
            if (!userList.contains(userName)) {
                userList.add(userName)
                sharedPrefs.edit()
                    .putString(KEY_USER_LIST, gson.toJson(userList))
                    .apply()
            }
            
            // 设置为当前用户
            setCurrentUser(userName)
            
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 更新现有用户数据
     */
    fun updateUserData(userName: String, personalDataJson: String, validationCode: String): Boolean {
        return try {
            val existingData = getUserData(userName)
            if (existingData != null) {
                val updatedData = existingData.copy(
                    personalDataJson = personalDataJson,
                    validationCode = validationCode,
                    lastUpdateTime = System.currentTimeMillis()
                    // 保持原有的userId不变
                )
                
                sharedPrefs.edit()
                    .putString("$KEY_USER_DATA_PREFIX$userName", gson.toJson(updatedData))
                    .apply()
                
                true
            } else {
                false
            }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 获取用户数据
     */
    fun getUserData(userName: String): UserData? {
        return try {
            val userDataJson = sharedPrefs.getString("$KEY_USER_DATA_PREFIX$userName", null)
            if (userDataJson != null) {
                gson.fromJson(userDataJson, UserData::class.java)
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 获取所有用户名列表
     */
    fun getAllUserNames(): List<String> {
        return try {
            val userListJson = sharedPrefs.getString(KEY_USER_LIST, null)
            if (userListJson != null) {
                val type = object : TypeToken<List<String>>() {}.type
                gson.fromJson(userListJson, type) ?: emptyList()
            } else {
                emptyList()
            }
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    /**
     * 获取所有用户数据
     */
    fun getAllUsers(): List<UserData> {
        val allUsers = getAllUserNames().mapNotNull { userName ->
            getUserData(userName)
        }
        
        val currentUserName = getCurrentUser()
        
        // 根据保存的顺序排序，如果没有保存顺序则按更新时间排序
        val savedOrder = getUserOrder()
        val orderedUsers = if (savedOrder.isNotEmpty()) {
            // 按保存的顺序排序
            val tempOrderedUsers = mutableListOf<UserData>()
            savedOrder.forEach { userName ->
                allUsers.find { it.userName == userName }?.let { tempOrderedUsers.add(it) }
            }
            // 添加不在已保存顺序中的新用户
            allUsers.forEach { user ->
                if (!tempOrderedUsers.contains(user)) {
                    tempOrderedUsers.add(user)
                }
            }
            tempOrderedUsers
        } else {
            // 默认按更新时间排序
            allUsers.sortedByDescending { it.lastUpdateTime }
        }
        
        // 确保当前用户永远在第一位
        return if (currentUserName != null) {
            val currentUser = orderedUsers.find { it.userName == currentUserName }
            val otherUsers = orderedUsers.filter { it.userName != currentUserName }
            if (currentUser != null) {
                listOf(currentUser) + otherUsers
            } else {
                orderedUsers
            }
        } else {
            orderedUsers
        }
    }
    
    /**
     * 删除用户数据
     */
    fun deleteUser(userName: String): Boolean {
        return try {
            // 删除用户数据
            sharedPrefs.edit()
                .remove("$KEY_USER_DATA_PREFIX$userName")
                .apply()
            
            // 从用户列表中移除
            val userList = getAllUserNames().toMutableList()
            userList.remove(userName)
            sharedPrefs.edit()
                .putString(KEY_USER_LIST, gson.toJson(userList))
                .apply()
            
            // 如果删除的是当前用户，清除当前用户设置
            if (getCurrentUser() == userName) {
                clearCurrentUser()
            }
            
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 设置当前用户
     */
    fun setCurrentUser(userName: String) {
        sharedPrefs.edit()
            .putString(KEY_CURRENT_USER, userName)
            .apply()
    }
    
    /**
     * 获取当前用户
     */
    fun getCurrentUser(): String? {
        return sharedPrefs.getString(KEY_CURRENT_USER, null)
    }
    
    /**
     * 获取当前用户ID
     */
    fun getCurrentUserId(): String? {
        val currentUserName = getCurrentUser()
        return if (currentUserName != null) {
            getUserData(currentUserName)?.userId
        } else {
            null
        }
    }
    
    /**
     * 清除当前用户
     */
    fun clearCurrentUser() {
        sharedPrefs.edit()
            .remove(KEY_CURRENT_USER)
            .apply()
    }
    
    /**
     * 检查用户名是否存在
     */
    fun userExists(userName: String): Boolean {
        return getAllUserNames().contains(userName)
    }
    
    /**
     * 获取用户数量
     */
    fun getUserCount(): Int {
        return getAllUserNames().size
    }
    
    /**
     * 格式化时间显示
     */
    fun formatTime(timestamp: Long): String {
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return formatter.format(Date(timestamp))
    }
    
    /**
     * 保存用户顺序
     */
    fun saveUserOrder(orderedUserNames: List<String>) {
        sharedPrefs.edit()
            .putString(KEY_USER_ORDER, gson.toJson(orderedUserNames))
            .apply()
    }
    
    /**
     * 获取用户顺序
     */
    fun getUserOrder(): List<String> {
        return try {
            val orderJson = sharedPrefs.getString(KEY_USER_ORDER, null)
            if (orderJson != null) {
                val type = object : TypeToken<List<String>>() {}.type
                gson.fromJson(orderJson, type) ?: emptyList()
            } else {
                emptyList()
            }
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    /**
     * 仅更新用户名（保持其他所有数据不变）
     */
    fun updateUserName(oldName: String, newName: String): Boolean {
        return try {
            val userData = getUserData(oldName)
            if (userData != null) {
                // 直接更新存储键名，不删除数据
                val oldKey = "$KEY_USER_DATA_PREFIX$oldName"
                val newKey = "$KEY_USER_DATA_PREFIX$newName"
                
                // 获取旧数据
                val oldDataJson = sharedPrefs.getString(oldKey, null)
                if (oldDataJson != null) {
                    // 创建新的UserData，只改变userName，其他所有字段保持不变
                    val updatedUserData = userData.copy(
                        userName = newName,
                        lastUpdateTime = System.currentTimeMillis()
                    )
                    
                    // 保存新键名的数据
                    sharedPrefs.edit()
                        .putString(newKey, gson.toJson(updatedUserData))
                        .remove(oldKey) // 删除旧键名
                        .apply()
                    
                    // 更新用户列表
                    val userList = getAllUserNames().toMutableList()
                    userList.remove(oldName)
                    userList.add(newName)
                    sharedPrefs.edit()
                        .putString(KEY_USER_LIST, gson.toJson(userList))
                        .apply()
                    
                    // 如果修改的是当前用户，更新当前用户设置
                    if (getCurrentUser() == oldName) {
                        setCurrentUser(newName)
                    }
                    
                    // 更新用户顺序（如果存在）
                    val savedOrder = getUserOrder()
                    if (savedOrder.isNotEmpty()) {
                        val updatedOrder = savedOrder.map { if (it == oldName) newName else it }
                        saveUserOrder(updatedOrder)
                    }
                    
                    true
                } else {
                    false
                }
            } else {
                false
            }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 清除所有用户数据
     */
    fun clearAllUsers() {
        val userList = getAllUserNames()
        userList.forEach { userName ->
            sharedPrefs.edit().remove("$KEY_USER_DATA_PREFIX$userName").apply()
        }
        sharedPrefs.edit()
            .remove(KEY_USER_LIST)
            .remove(KEY_CURRENT_USER)
            .remove(KEY_USER_ORDER)
            .apply()
    }
} 